package com.photography.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import com.photography.entity.User;
import com.photography.entity.Photographers;
import com.photography.service.UserService;
import com.photography.service.PhotographersService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

@Component
public class JwtTokenUtils {
    private static UserService staticUserService;
    private static PhotographersService staticPhotographersService;
    private static final Logger log=LoggerFactory.getLogger(JwtTokenUtils.class);

    @Resource
    private UserService userService;

    @Resource
    private PhotographersService photographersService;

    @PostConstruct
    public void setServices(){
        staticUserService = userService;
        staticPhotographersService = photographersService;
    }

    //    生成Token
    public static String getToken(String userId, String sign, String role){
        return JWT.create()
                .withAudience(userId)
                .withClaim("role", role)  // 添加角色信息
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))  // 2小时后过期
                .sign(Algorithm.HMAC256(sign));//以password作为token的密钥
    }

    //获取当前登录的用户信息
    public static User getCurrentUser(){
        String token=null;
        try{
            HttpServletRequest request= (HttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getHeader("token");
            if (StrUtil.isBlank(token)){
                token=request.getParameter("token");
            }
            if (StrUtil.isBlank(token)){
                log.error("获取登录token失败，token：{}",token);
                return null;
            }
            //解析token
            String adminId= JWT.decode(token).getAudience().get(0);
            return staticUserService.getById(Integer.valueOf(adminId));
        }catch (Exception e){
            log.error("获取信息失败，token：{}",token,e);
            return null;
        }
    }

    //获取当前登录的摄影师信息
    public static Photographers getCurrentPhotographer(){
        String token=null;
        try{
            HttpServletRequest request= (HttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getHeader("token");
            if (StrUtil.isBlank(token)){
                token=request.getParameter("token");
            }
            if (StrUtil.isBlank(token)){
                log.error("获取登录token失败，token：{}",token);
                return null;
            }
            //解析token
            String photographerId= JWT.decode(token).getAudience().get(0);
            return staticPhotographersService.getById(Integer.valueOf(photographerId));
        }catch (Exception e){
            log.error("获取信息失败，token：{}",token,e);
            return null;
        }
    }

    /**
     * 获取当前登录用户的角色
     * @return 角色名称，如果未登录返回null
     */
    public static String getCurrentRole() {
        try {
            HttpServletRequest request = (HttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isBlank(token)) {
                token = request.getParameter("token");
            }
            if (StrUtil.isBlank(token)) {
                return null;
            }
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("role").asString();
        } catch (Exception e) {
            log.error("获取角色信息失败", e);
            return null;
        }
    }
}
